import 'package:flutter/material.dart';
import 'package:flutter_wisave/CentrePage/Energy/PolluteDetail.dart';
import 'ContaminateItem.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../../widgets/AppColors.dart';

class ContaminateView extends StatefulWidget {
  const ContaminateView({super.key});

  @override
  _ContaminateViewState createState() => _ContaminateViewState();
}

class _ContaminateViewState extends State<ContaminateView> {
  final NetworkService _networkService = NetworkService();
  List<dynamic> pollutantData = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result != null && result['data'] != null) {
        setState(() {
          if (result['data'] is List) {
            pollutantData = result['data'];
          } else if (result['data'] is Map) {
            pollutantData = [result['data']];
          } else {
            print('未知的数据类型: ${result['data'].runtimeType}');
          }
        });
      } else {
        print('未从_fetchData接收到数据');
      }
    } catch (e) {
      print('_loadData错误: $e');
    }
  }

  Future<Map<String, dynamic>?> _fetchData() async {
    try {
      final response =
          await _networkService.get('/plcTimer/pollutanthour/pollutantHour');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('加载数据失败: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('_fetchData错误: $e');
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
      decoration: const BoxDecoration(
        color: Colors.transparent,
      ),
      child: Column(
        children: [
          const SizedBox(height: 10),
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: pollutantData.length,
            itemBuilder: (context, index) {
              final item = pollutantData[index];
              return GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => PolluteDetail(),
                    ),
                  );
                },
                child: ContaminateItem(
                  icon: 'assets/images/centre/so2.png',
                  name: item['name'] ?? 'SO₂',
                  actualValue: ('实际值：' + (item['so2Avg']?.toString() ?? '0')),
                  standardValue: ('国标：' + (item['noxAvg']?.toString() ?? '0')),
                  status: item['status'] ?? '正常',
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
